
import logging
from rest_framework import status
from rest_framework.response import Response
from py_web.common.constant.SecurityConstant import START
from py_web.security.SecuritySerialization import  RoleMenuSerializer, \
     MenuSerializer, MenuTreeselectSerializer
from py_web.security.models import  Role,  Menu
from py_web.user.Serialization import SaveOrUpdateRoleMenuSerializer
from utils.StrUtil import isNotBlank, isNotEmpty

logger = logging.getLogger('log')


# Create your views here.
# 公共方法

# 查询三层菜单父子关系
def roleMenuTreeselect():
    # 三层结构分别是：目录-》菜单-》按钮
    # 关键字段：id、menuname、parentId、children[{id、menuname、parentId}]
    # {"tree":[{"m1id":1,"m1name":"aa","m1pid":0,"children":[{"m2id":2,"m2name":"bb","m2pid":1,"children":[{"m3id":5,"m3name":"ee","m3pid":2,"children":[{}]}]},{"m2id":3,"m2name":"cc","m2pid":1,"children":[{}]},{"m2id":4,"m2name":"dd","m2pid":1,"children":[{}]}]}]}
    menu = (Menu.objects
            .filter(status=START)
            .order_by('orderNum'))

    menus = MenuTreeselectSerializer(menu, many=True).data

    all: dict = {}
    trees = []

    # 第一层
    for m in menus:
        if m['parentId'] == 0:
            # 保证有children这么个字段
            m['children'] = []
            trees.append(m)
        all[m['menuId']] = m

    # 第二层
    for m in menus:
        try:
            # 如果查不到会报错
            parent = all[m['parentId']]
        except:
            continue
        try:
            parent['children']
        except:
            parent['children'] = []
        m['children'] = []
        # 组装树信息
        parent['children'].append(m)

    # 第三层
    threeMenus = []
    for m in menus:
        if m['menuType'] is 'F':
            threeMenus.append(m)

    for tree in trees:
        for twomenu in tree['children']:
            for threeMenu in threeMenus:
                if threeMenu['parentId'] is twomenu['menuId']:
                    twomenu['children'].append(threeMenu)
    return trees


# 新增或更新角色
def SaveOrUpdateRole(request, stat):
    serializer = None
    if stat is "U":
        role = Role.objects.get(roleId=request.data['roleId'])
        serializer = SaveOrUpdateRoleMenuSerializer(instance=role, data=request.data)
    elif stat is "S":
        serializer = SaveOrUpdateRoleMenuSerializer(data=request.data)

    serializer.is_valid(raise_exception=True)
    serializer.save()
    serializer = serializer.data

    # 保存角色菜单关联表
    menuIds: list = request.data['menuIds']
    if isNotEmpty(menuIds):
        roleId = serializer['roleId']
        for menuId in menuIds:
            roleMenuEntity = {
                "menuId": menuId,
                "roleId": roleId,
            }
            serializer = RoleMenuSerializer(data=roleMenuEntity)
            serializer.is_valid(raise_exception=True)
            serializer.save()
    return Response(status=status.HTTP_200_OK)



# 新增或更新菜单
def saveOrUpdateMenu(request, stu):

    menuType = request.data['menuType']
    if menuType is 'M':
        request.data['parentId'] = 0
    elif menuType is 'F':
        request.data['parentId'] = request.data['menuLeveupId'][0]
    else:
        request.data['parentId'] = request.data['menuLeveupId']

    serializers = None
    if stu is "S":
        serializers = MenuSerializer(data=request.data)
    elif stu is "U":
        menu = Menu.objects.get(menuId=request.data['menuId'])
        serializers = MenuSerializer(instance=menu, data=request.data)

    if serializers.is_valid():
        serializers.save()


